package org.wu.framework.lazy.orm.database.lambda.dynamic;


import org.wu.framework.lazy.database.datasource.proxy.LazyProxyDataSource;
import org.wu.framework.lazy.database.datasource.proxy.connection.LazyProxyConnection;
import org.wu.framework.lazy.database.datasource.proxy.handler.JdbcHandlerAdapter;
import org.wu.framework.lazy.database.datasource.proxy.util.LazyDataSourceProxyUtils;
import org.wu.framework.lazy.orm.core.config.prop.LazyDataSourceAttribute;
import org.wu.framework.lazy.orm.core.persistence.conf.LazyDynamicEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.lazy.orm.database.lambda.dynamic.toolkit.DynamicLazyDSContextHolder;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;

/**
 * describe : lazy 动态数据源适配器
 *
 * @author : Jia wei Wu
 * @version 1.0
 * @date : 2022/1/29 20:28
 */
@Slf4j
public class LazyDynamicDatasourceAdapter extends AbstractDynamicDatasourceAdapter {

    private final JdbcHandlerAdapter jdbcHandlerAdapter;
    public LazyDynamicDatasourceAdapter(Map<String, LazyProxyDataSource> dataSourceMap, JdbcHandlerAdapter jdbcHandlerAdapter) {
        super(dataSourceMap, jdbcHandlerAdapter);
        this.jdbcHandlerAdapter = jdbcHandlerAdapter;

    }

    /**
     * describe 确定数据源
     *
     * @return DataSource 返回数据源
     * @author Jia wei Wu
     * @date 2021/7/4 6:19 下午
     **/
    @Override
    public LazyProxyDataSource determineDataSource() {
        final String primary = getPrimary();
        final Map<String, LazyProxyDataSource> dataSourceMap = getDataSourceMap();
        LazyDynamicEndpoint ds = DynamicLazyDSContextHolder.peek();
        if (ObjectUtils.isEmpty(ds)) {
            if (dataSourceMap.keySet().size() > 1) {
                log.debug("当前方法没有设置默认值,将使用默认数据源master:{} ", primary);
            }

        } else if (!ObjectUtils.isEmpty(ds.getName()) && dataSourceMap.containsKey(ds.getName())) {
            return dataSourceMap.get(ds.getName());
        } else {
            log.debug("无法使用数据源{} 将使用默认数据源master:{} ", ds, primary);
        }
        return dataSourceMap.get(primary);
    }

    /**
     * 确定数据源连接对象
     *
     * @return 数据源连接对象
     * @see DynamicDatasourceAdapter#determineDataSource()
     */
    @Override
    public LazyProxyConnection determineConnection() throws SQLException {
        LazyProxyDataSource dataSource = determineDataSource();//
        return dataSource.getLazyConnection();
    }

    /**
     * 数据源载入
     *
     * @param sourceProperties 数据源参数
     */
    @Override
    public void loading(LazyDataSourceAttribute sourceProperties) {
        DataSource build = sourceProperties.getDatasource();
        getDataSourceMap().put(sourceProperties.getAlias(), LazyDataSourceProxyUtils.proxy(build, jdbcHandlerAdapter));
    }
}
